package com.xhs.util;

import cn.hutool.http.HttpRequest;
import com.xhs.config.ProxyConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.net.Authenticator;

/**
 * 代理工具类
 *
 * @author xhs
 */
@Slf4j
@Component
public class ProxyUtil {

    @Autowired
    private ProxyConfig proxyConfig;

    @PostConstruct
    public void initProxy() {
        if (proxyConfig.isConfigured()) {
            // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
            
            // 设置请求验证信息（仅在有用户名密码时设置）
            if (hasProxyCredentials()) {
                Authenticator.setDefault(new ProxyAuthenticator(proxyConfig.getUsername(), proxyConfig.getPassword()));
                log.info("代理配置已准备就绪（带认证）: {}:{}", proxyConfig.getHost(), proxyConfig.getPort());
            } else {
                log.info("代理配置已准备就绪（白名单模式）: {}:{}", proxyConfig.getHost(), proxyConfig.getPort());
            }
            log.info("代理仅在特定功能中使用：发送验证码、登录、小红书笔记搜索");
        } else {
            log.info("代理配置未启用或配置不完整");
        }
    }

    /**
     * 检查是否有代理认证信息
     */
    private boolean hasProxyCredentials() {
        return proxyConfig.getUsername() != null && !proxyConfig.getUsername().trim().isEmpty() &&
               proxyConfig.getPassword() != null && !proxyConfig.getPassword().trim().isEmpty();
    }

    /**
     * 为HttpRequest设置代理
     */
    public HttpRequest setProxy(HttpRequest request) {
        if (proxyConfig.isConfigured()) {
            return request.setHttpProxy(proxyConfig.getHost(), proxyConfig.getPort())
                          .timeout(proxyConfig.getTimeout());
        }
        return request.timeout(proxyConfig.getTimeout());
    }

    /**
     * 获取代理配置
     */
    public ProxyConfig getProxyConfig() {
        return proxyConfig;
    }
} 